package tr.edu.ege.kipler.satisfiability.container.operational;

import java.util.Comparator;

import tr.edu.ege.kipler.satisfiability.container.Individual;
import tr.edu.ege.kipler.satisfiability.container.SHIQABox;

/**
 * 
 * @author İnanç Seylan
 *
 */
public class IndividualNameComparator implements Comparator<Individual> {
	private SHIQABox aBox;

	public IndividualNameComparator(SHIQABox abox) {
		setABox(abox);
	}

	public SHIQABox getABox() {
		return aBox;
	}

	public void setABox(SHIQABox box) {
		aBox = box;
	}

	public int compare(Individual arg0, Individual arg1) {
		int result;
		if (arg0.equals(arg1)) {
			result = 0;
		} else if (getABox().isRoot(arg0) && getABox().isRoot(arg1)) {
			result = compareRoots(arg0, arg1);
		} else if (getABox().isRoot(arg0)) {
			result = -1;
		} else if (getABox().isRoot(arg1)) {
			result = 1;
		} else {
			result = isLessThan(arg0.getName(), arg1.getName()) ? -1 : 1;
		}
		return result;
	}

	private int compareRoots(Individual arg0, Individual arg1) {
		int result;
		if (isOldIndividual(arg0) && isOldIndividual(arg1)) {
			result = arg0.getName().compareTo(arg1.getName());
		} else if (isOldIndividual(arg0)) {
			result = -1;
		} else if (isOldIndividual(arg1)) {
			result = 1;
		} else {
			result = isLessThan(arg0.getName(), arg1.getName()) ? -1 : 1;
		}
		return result;
	}

	public boolean isOldIndividual(Individual indv) {
		return getNo(indv.getName()) == -1;
	}

	public boolean isLessThan(String indv1, String indv2) {
		return getNo(indv1) < getNo(indv2);
	}

	private int getNo(String individual) {
		int result = -1;
		if (individual.startsWith(" x")) {
			result = Integer.parseInt(individual.substring(2));
		}
		return result;
	}

}
